import React, { FC, Suspense } from 'react';
import { Route, Switch } from 'react-router-dom';
import { RouteType } from './routes';
import AsyncLoader from './async-loader';

export interface ISubRoutes {
  routes: Array<RouteType>;
  handlePathMatched: Function;
}

const RouteWithSubRoutes: FC<ISubRoutes> = (props) => {
  const { routes, handlePathMatched } = props;
  return (
    <Suspense fallback={<div className="div-loading-class">loading</div>}>
      <Switch>
        {routes.map((route: RouteType) => {
          if (process.env.NODE_ENV !== 'production') {
            if (route.component === undefined) {
              throw new Error(
                `${route.path} can not find component or asyncComponent`
              );
            }
          }
          const {
            title,
            component,
            subRoutes,
            hasBottom,
            withoutLogin,
            openAccess,
            name,
            ...rest
          } = route;
          return (
            <Route
              key={name}
              {...rest}
              render={(props: any) => (
                <AsyncLoader
                  {...props}
                  title={title}
                  component={component}
                  subRoutes={subRoutes}
                  hasBottom={hasBottom}
                  handlePathMatched={handlePathMatched}
                />
              )}
            />
          );
        })}
      </Switch>
    </Suspense>
  );
};

export default RouteWithSubRoutes;
